<template>
	<view class="article-detail">
		<!-- 加载中提示 -->
		<view class="loading-container" v-if="loading">
			<t-loading theme="circular" size="80rpx" text="加载中..." />
		</view>
		
		<!-- 错误状态 -->
		<view class="error-state" v-if="error">
			<image src="/static/images/error-state.png" mode="aspectFit" class="error-image"></image>
			<text class="error-text">加载失败，请稍后重试</text>
			<button class="retry-btn" @tap="loadArticleDetail">重新加载</button>
		</view>
		
		<!-- 文章主体 -->
		<view v-if="article && !loading && !error">
			<!-- 文章封面图 -->
			<image 
				:src="article.coverImage || '/static/images/placeholder.png'" 
				mode="aspectFill" 
				class="article-cover"
			></image>
			
			<view class="article-container">
				<!-- 文章头部信息 -->
				<view class="article-header">
					<view class="article-title">{{ article.title }}</view>
					<view class="article-meta">
						<view class="meta-item">
							<t-icon name="user" size="28rpx" color="#8cc9a1"></t-icon>
							<text>{{ article.author }}</text>
						</view>
						<view class="meta-item">
							<t-icon name="browse" size="28rpx" color="#8cc9a1"></t-icon>
							<text>{{ article.viewCount || 0 }} 阅读</text>
						</view>
						<view class="meta-item">
							<t-icon name="time" size="28rpx" color="#8cc9a1"></t-icon>
							<text>{{ formatDate(article.publishDate) }}</text>
						</view>
					</view>
					
					<!-- 文章标签 -->
					<view class="article-tags" v-if="article.tags && article.tags.length">
						<text class="tag" v-for="(tag, index) in article.tags" :key="index">{{ tag }}</text>
					</view>
				</view>
				
				<!-- 文章摘要 -->
				<view class="article-summary" v-if="article.summary">
					<text>{{ article.summary }}</text>
				</view>
				
				<!-- 文章内容 -->
				<view class="article-content">
					<rich-text :nodes="formattedContent" class="article-body"></rich-text>
				</view>
				
				<!-- 作者信息卡片 -->
				<view class="author-card">
					<view class="author-header">
						<image src="/static/images/doctor-avatar.png" class="author-avatar"></image>
						<view class="author-details">
							<view class="author-name">{{ article.author }}</view>
							<view class="author-title">{{ article.authorTitle || '医学专家' }}</view>
							<view class="author-hospital" v-if="article.hospital">{{ article.hospital }} {{ article.department }}</view>
						</view>
					</view>
					<view class="author-bio" v-if="article.authorBio">
						{{ article.authorBio }}
					</view>
				</view>
				
				<!-- 相关推荐 -->
				<view class="related-articles" v-if="relatedArticles.length > 0">
					<view class="section-title">
						<text>相关推荐</text>
					</view>
					<view class="related-list">
						<view 
							class="related-item" 
							v-for="item in relatedArticles" 
							:key="item.id"
							@tap="viewRelatedArticle(item)"
						>
							<image :src="item.coverImage || '/static/images/placeholder.png'" class="related-image" mode="aspectFill"></image>
							<view class="related-info">
								<view class="related-title">{{ item.title }}</view>
								<view class="related-meta">
									<text>{{ item.viewCount || 0 }} 阅读</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 返回按钮 -->
		<view class="back-button" @tap="goBack">
			<t-icon name="chevron-left" size="40rpx" color="#fff"></t-icon>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import { getArticleDetail } from '@/common/api/article.js'
	
	// 状态定义
	const articleId = ref(null)
	const article = ref(null)
	const relatedArticles = ref([])
	const loading = ref(true)
	const error = ref(false)
	const formattedContent = ref('')
	
	// 加载文章详情
	const loadArticleDetail = async () => {
		if (!articleId.value) {
			console.error('文章ID为空')
			error.value = true
			loading.value = false
			return
		}
		
		loading.value = true
		error.value = false
		
		try {
			console.log('开始加载文章详情, ID:', articleId.value)
			const res = await getArticleDetail(articleId.value)
			console.log('文章详情API返回:', JSON.stringify(res).substring(0, 300) + '...')
			
			if (res.code === 0 && res.data) {
				article.value = res.data.article
				relatedArticles.value = res.data.relatedArticles || []
				
				// 格式化文章内容
				if (article.value && article.value.content) {
					formattedContent.value = formatArticleContent(article.value.content)
				}
				
				console.log('文章标题:', article.value?.title)
				console.log('文章内容长度:', article.value?.content ? article.value.content.length : 0)
				
				// 设置页面标题
				if (article.value?.title) {
					uni.setNavigationBarTitle({
						title: article.value.title
					})
				}
			} else {
				throw new Error(res.message || '加载失败')
			}
		} catch (e) {
			console.error('加载文章详情失败:', e)
			uni.showToast({
				title: '加载文章失败',
				icon: 'none'
			})
			error.value = true
		} finally {
			loading.value = false
		}
	}
	
	// 格式化文章内容，处理HTML内容
	const formatArticleContent = (content) => {
		console.log('格式化文章内容:', content ? content.substring(0, 100) + '...' : '无内容')
		if (!content) return ''
		
		// 如果内容已经是HTML格式，直接返回
		if (content.indexOf('<') !== -1 && content.indexOf('>') !== -1) {
			// 增强HTML内容的样式
			return content
				.replace(/<p/g, '<p style="margin-bottom: 24rpx; line-height: 1.8;"')
				.replace(/<h1/g, '<h1 style="font-size: 40rpx; font-weight: bold; margin: 40rpx 0 20rpx; color: #333;"')
				.replace(/<h2/g, '<h2 style="font-size: 36rpx; font-weight: bold; margin: 36rpx 0 18rpx; color: #333;"')
				.replace(/<h3/g, '<h3 style="font-size: 32rpx; font-weight: bold; margin: 32rpx 0 16rpx; color: #333;"')
				.replace(/<img/g, '<img style="max-width: 100%; border-radius: 12rpx; margin: 20rpx 0;"')
				.replace(/<ul/g, '<ul style="padding-left: 40rpx; margin-bottom: 24rpx;"')
				.replace(/<ol/g, '<ol style="padding-left: 40rpx; margin-bottom: 24rpx;"')
				.replace(/<li/g, '<li style="margin-bottom: 16rpx;"')
				.replace(/<a/g, '<a style="color: #8cc9a1; text-decoration: underline;"')
		}
		
		// 将纯文本转换为HTML格式
		return content.split('\n').map(line => `<p style="margin-bottom: 24rpx; line-height: 1.8;">${line}</p>`).join('')
	}
	
	// 格式化日期
	const formatDate = (dateString) => {
		if (!dateString) return ''
		
		try {
			const date = new Date(dateString)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		} catch (e) {
			return dateString
		}
	}
	
	// 查看相关文章
	const viewRelatedArticle = (item) => {
		uni.navigateTo({
			url: `/pages/articles/detail?id=${item.id}`
		})
	}
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
	
	// 页面加载
	onMounted(() => {
		// 获取路由参数
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		
		// 尝试多种方式获取文章ID
		const id = currentPage.options?.id || currentPage.$page?.options?.id
		
		if (id) {
			articleId.value = id
			console.log('成功获取到文章ID:', articleId.value)
			// 加载文章详情
			loadArticleDetail()
		} else {
			console.error('无法获取文章ID，尝试从URL中解析')
			// 尝试从URL中解析ID
			const url = currentPage.$page?.fullPath || ''
			const match = url.match(/id=([^&]+)/)
			if (match && match[1]) {
				articleId.value = match[1]
				console.log('从URL中解析到文章ID:', articleId.value)
				loadArticleDetail()
			} else {
				// 显示错误信息
				error.value = true
				loading.value = false
				uni.showToast({
					title: '无法获取文章ID',
					icon: 'none'
				})
			}
		}
	})
</script>

<style lang="scss">
	.article-detail {
		position: relative;
		min-height: 100vh;
		background-color: #f5f7fa;
		
		.article-cover {
			width: 100%;
			height: 450rpx;
			display: block;
		}
		
		.article-container {
			background-color: #fff;
			margin-top: -60rpx;
			border-radius: 40rpx 40rpx 0 0;
			padding: 40rpx 30rpx;
			position: relative;
			
			.article-header {
				margin-bottom: 30rpx;
				
				.article-title {
					font-size: 40rpx;
					font-weight: bold;
					color: #333;
					line-height: 1.4;
					margin-bottom: 24rpx;
				}
				
				.article-meta {
					display: flex;
					flex-wrap: wrap;
					margin-bottom: 24rpx;
					
					.meta-item {
						display: flex;
						align-items: center;
						margin-right: 24rpx;
						margin-bottom: 12rpx;
						
						text {
							font-size: 24rpx;
							color: #666;
							margin-left: 8rpx;
						}
					}
				}
				
				.article-tags {
					display: flex;
					flex-wrap: wrap;
					
					.tag {
						background-color: rgba(140, 201, 161, 0.1);
						color: #8cc9a1;
						font-size: 24rpx;
						padding: 6rpx 20rpx;
						border-radius: 30rpx;
						margin-right: 16rpx;
						margin-bottom: 16rpx;
					}
				}
			}
			
			.article-summary {
				background-color: #f9f9f9;
				border-left: 8rpx solid #8cc9a1;
				padding: 24rpx;
				margin-bottom: 40rpx;
				border-radius: 0 16rpx 16rpx 0;
				
				text {
					font-size: 28rpx;
					color: #666;
					line-height: 1.6;
					font-style: italic;
				}
			}
			
			.article-content {
				margin-bottom: 40rpx;
			}
			
			.article-body {
				font-size: 30rpx;
				color: #333;
				line-height: 1.8;
			}
			
			.author-card {
				background-color: #f9f9f9;
				border-radius: 20rpx;
				padding: 30rpx;
				margin-bottom: 40rpx;
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
				
				.author-header {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					
					.author-avatar {
						width: 100rpx;
						height: 100rpx;
						border-radius: 50%;
						margin-right: 20rpx;
						border: 4rpx solid rgba(140, 201, 161, 0.2);
					}
					
					.author-details {
						.author-name {
							font-size: 32rpx;
							font-weight: bold;
							color: #333;
							margin-bottom: 8rpx;
						}
						
						.author-title {
							font-size: 26rpx;
							color: #8cc9a1;
							margin-bottom: 4rpx;
						}
						
						.author-hospital {
							font-size: 24rpx;
							color: #999;
						}
					}
				}
				
				.author-bio {
					font-size: 26rpx;
					color: #666;
					line-height: 1.6;
				}
			}
			
			.related-articles {
				margin-bottom: 40rpx;
				
				.section-title {
					position: relative;
					margin-bottom: 30rpx;
					padding-left: 20rpx;
					
					text {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}
					
					&::before {
						content: '';
						position: absolute;
						left: 0;
						top: 6rpx;
						bottom: 6rpx;
						width: 8rpx;
						background-color: #8cc9a1;
						border-radius: 4rpx;
					}
				}
				
				.related-list {
					.related-item {
						display: flex;
						padding: 20rpx 0;
						border-bottom: 1px solid #f0f0f0;
						
						&:last-child {
							border-bottom: none;
						}
						
						.related-image {
							width: 160rpx;
							height: 120rpx;
							border-radius: 12rpx;
							margin-right: 20rpx;
						}
						
						.related-info {
							flex: 1;
							display: flex;
							flex-direction: column;
							justify-content: space-between;
							
							.related-title {
								font-size: 28rpx;
								color: #333;
								font-weight: 500;
								line-height: 1.4;
								
								// 最多显示两行
								display: -webkit-box;
								-webkit-line-clamp: 2;
								-webkit-box-orient: vertical;
								overflow: hidden;
							}
							
							.related-meta {
								font-size: 24rpx;
								color: #999;
							}
						}
					}
				}
			}
		}
		
		.back-button {
			position: fixed;
			top: 60rpx;
			left: 30rpx;
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			background-color: rgba(0, 0, 0, 0.3);
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 100;
		}
		
		.loading-container, .error-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100vh;
			
			.error-image {
				width: 240rpx;
				height: 240rpx;
				margin-bottom: 30rpx;
			}
			
			.error-text {
				font-size: 30rpx;
				color: #999;
				margin-bottom: 30rpx;
			}
			
			.retry-btn {
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				padding: 12rpx 40rpx;
				border-radius: 40rpx;
			}
		}
	}
</style> 